<template>
    <div ref="textContainer" class="textFor404"></div>
    <Button3 v-if="showButton" @click="goHome" class="home-button">
    <div>
        返回主页
    </div>
</Button3> 
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import Button3 from '@/components/button3.vue'

const router = useRouter();
const textContainer = ref(null);
const showButton = ref(false);

const strings = [
    "404 NOT FOUND!<br />",
    "Oops! 你好像走丢了，<br />",
    "非常抱歉喵，<br />",
    "请返回主页重新开始，谢谢喵。"
];

//打字速度,100ms一个字
const typeSpeed = 100;
const showCursor = false;

onMounted(() => {
    typewrite(strings.join(''), textContainer.value);
});

//打字效果，递归调用打字
function typewrite(text, container, index = 0) {
    if (index < text.length) {
        //获取下一个字符
        const nextChar = text.charAt(index);

        //处理 <br/> 标签
        if (nextChar === '<') {
            const endTagIndex = text.indexOf('>', index);
            const tag = text.slice(index, endTagIndex + 1);
            container.innerHTML += tag;
            setTimeout(() => typewrite(text, container, endTagIndex + 1), typeSpeed);
        }
        //正常打字
        else {
            container.innerHTML += nextChar;
            setTimeout(() => typewrite(text, container, index + 1), typeSpeed);
        }
    }
    else { 
        if (showCursor)
            container.innerHTML += '<span class="typed-cursor">|</span>';
        //控制按钮显示
        showButton.value = true;
    }
}

//返回主页
function goHome() {
    router.push('/');
}
</script>

<style scoped>
.textFor404 {
    color: #fff;
}

.typed-cursor {
    display: inline-block;
    animation: blink 1s infinite;
}

@keyframes blink {

    0%,
    50% {
        opacity: 1;
    }

    50%,
    100% {
        opacity: 0;
    }
}

.home-button {
    display: block;
    margin: 20px auto 0;
    padding: 10px 20px;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    text-align: center;
    opacity: 0;
    animation: fadeIn 2s forwards;
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    bottom: 20px;
}



@keyframes fadeIn {
    from {
        opacity: 0;
    }

    to {
        opacity: 1;
    }
}
</style>